import React, { useState, useEffect } from "react";
import { useHistory } from "react-router-dom";
import s from "./style.module.less";
import { get } from "@/utils";
import cx from "classnames";
import * as echarts from "echarts";

// 全局配置 echart 变量
let proportionChart = null;

const User = () => {
  

  const [userName, setUserName] = useState("测试用名");
  const [userSign, setUserSign] = useState("这里可以编辑个性签名哦~");
  const [userAvatar, setUserAvatar] = useState("");
  const [pieType, setPieType] = useState("expend");
  const history = useHistory();

  useEffect(async () => {
    getUserMsg();
  }, []);
  useEffect(async () => {
    changePieType("expend");
  }, []);

  const getUserMsg = async () => {
    const { data } = await get("/api/user/showUserMsg");
    // console.log('看看能不能获取', data);
    setUserName(data.userInfoMsg.username);
    setUserSign(data.userInfoMsg.sign);
    setUserAvatar(data.userInfoMsg.avatar);
  };
  const goToUserinfoChange = () => {
    history.push("/cuserinfo");
    // window.location.href = '/cuserinfo'
  };

  const goToChangePassword = () => {
    history.push("/cpassword");
  };

  // 类别
  const itemTypes = (data) => {
    // 接收的传入的data，为请求到的总收入/总支出
    // 待会儿要展示的类别，为data里每个对象的type_id属性
    let type = new Map();
    let types = [];
    data.forEach((item) => {
      if (!type.get(item.type_name)) {
        type.set(item.type_name, +item.amount);
      }
      type.set(item.type_name, +item.amount + type.get(item.type_name));
    });
    type.forEach(function (val, key) {
      var i = {
        type: key,
        value: val,
      };
      types.push(i);
    });
    console.log(types, "echart返回数据");
    return types;
  };

  // 绘制饼图
  const setPieChart = async (data) => {
    proportionChart = echarts.init(document.getElementById("proportion"));
    proportionChart.setOption({
      // 提示框
      tooltip: {
        trigger: "item",
        formatter: "{a} <br/>{b} : {c} ({d}%)",
      },
      // 图例
      legend: {
        data: data.map((item) => item.type),
      },
      series: [
        {
          name: "详情",
          type: "pie",
          radius: "50%",
          data: data.map((item) => {
            return {
              value: item.value,
              name: item.type,
            };
          }),
          roseType: false, //是否设置为南丁格尔图
          emphasis: {
            itemStyle: {
              shadowBlur: 10,
              shadowOffsetX: 0,
              shadowColor: "rgba(0, 0, 0, 0.5)",
            },
          },
        },
      ],
    });
  };

  // 切换饼图类型
  const changePieType = async (type) => {
    setPieType(type);
    let pay_type; // 1为支出  2位收入
    if (type == "expend") {
      // 请求账单支出数据
      pay_type = 1; //请求类型为支出
      const { data } = await get(`/api/bill/getAllNumber?pay_type=${pay_type}`);
      console.log("哈哈哈1", data);
      // 根据获取到的数据，设置饼图
      setPieChart(itemTypes(data));
    } else {
      pay_type = 2; //请求类型为收入
      const { data } = await get(`/api/bill/getAllNumber?pay_type=${pay_type}`);
      console.log("哈哈哈2", data);
      // 根据获取到的数据，设置饼图
      setPieChart(itemTypes(data));
    }
  };

  return (
    <div className={s.user}>
      <div className={s.header}>
        <div className={s.headerLeft}>
          <div className={s.headerName}>{userName}</div>
          <div className={s.headerSign}>{userSign}</div>
        </div>
        <div className={s.headerRight}>
          <div className={s.headerImg}>
            <img src={userAvatar} alt="" />
          </div>
        </div>
      </div>
      <div className={s.content}>
        {/* 修改头像和签名 */}
        <div
          className={s.contentItem}
          onClick={() => {
            goToUserinfoChange();
          }}
        >
          <div className={s.contentItemIcon}>
            <img src="http://s.yezgea02.com/1615974766264/gxqm.png" />
          </div>
          <div className={s.contentItemText}>用户信息修改</div>
        </div>
        {/* 修改密码 */}
        <div
          className={s.contentItem}
          onClick={() => {
            goToChangePassword();
          }}
        >
          <div className={s.contentItemIcon}>
            <img src="http://s.yezgea02.com/1615974766264/zhaq.png" />
          </div>
          <div className={s.contentItemText}>重置密码</div>
        </div>

        {/* 展示饼图 */}
        <div className={s.proportion}>
          <div className={s.subHead}>
            <span className={s.title}>大数据饼图</span>
            <div className={s.tab}>
              <span
                onClick={() => changePieType("expend")}
                className={cx({
                  [s.expense]: true,
                  [s.active]: pieType == "expend",
                })}
              >
                支出
              </span>
              <span
                onClick={() => changePieType("income")}
                className={cx({
                  [s.expense]: true,
                  [s.active]: pieType == "income",
                })}
              >
                收入
              </span>
            </div>
          </div>

          {/* 饼图展示 */}
          <div id="proportion"></div>
        </div>
      </div>
    </div>
  );
};

export default User;
